package com.copd.controller;

import com.copd.common.ApiResponse;
import com.copd.dto.RestoreDataRequest;
import com.copd.service.DataRestoreService;
import com.copd.service.DoctorOperationLogService;
import com.copd.util.JwtUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Api(tags = "患者数据恢复接口")
@RestController
@RequestMapping("/api/restore")
public class DataRestoreController {
    
    private static final Logger logger = LoggerFactory.getLogger(DataRestoreController.class);
    
    @Autowired
    private DataRestoreService dataRestoreService;
    
    @Autowired
    private DoctorOperationLogService logService;
    
    @Autowired
    private JwtUtil jwtUtil;
    
    /**
     * 从备份恢复患者数据
     */
    @ApiOperation(value = "恢复患者数据", notes = "从备份表恢复指定患者的数据到原表中，会覆盖原表中的数据")
    @PostMapping("/patient")
    public ResponseEntity<?> restorePatientData(
            @RequestBody RestoreDataRequest request,
            HttpServletRequest httpRequest) {
        
        try {
            logger.info("收到恢复患者数据请求: {}", request);
            
            // 从请求中获取当前登录医生ID
            Integer doctorId = getCurrentDoctorId(httpRequest);
            if (doctorId == null) {
                return ResponseEntity.badRequest().body(
                    ApiResponse.error("无法获取当前登录医生ID")
                );
            }
            
            // 参数校验
            if (request.getPatientId() == null) {
                return ResponseEntity.badRequest().body(
                    ApiResponse.error("患者ID不能为空")
                );
            }
            
            if (request.getTables() == null || request.getTables().isEmpty()) {
                return ResponseEntity.badRequest().body(
                    ApiResponse.error("要恢复的表列表不能为空")
                );
            }
            
            // 恢复数据
            Map<String, Object> result = dataRestoreService.restorePatientData(
                request.getPatientId(), 
                doctorId, 
                request.getTables()
            );
            
            if ((boolean) result.get("success")) {
                return ResponseEntity.ok(ApiResponse.success(result));
            } else {
                return ResponseEntity.badRequest().body(
                    ApiResponse.error((String) result.get("message"), result)
                );
            }
        } catch (Exception e) {
            logger.error("恢复患者数据时发生错误", e);
            return ResponseEntity.badRequest().body(
                ApiResponse.error("恢复患者数据时发生错误: " + e.getMessage())
            );
        }
    }
    
    /**
     * 验证恢复请求的有效性
     */
    @ApiOperation(value = "验证恢复请求", notes = "验证指定患者的恢复请求是否有效")
    @PostMapping("/validate")
    public ResponseEntity<?> validateRestoreRequest(
            @RequestBody RestoreDataRequest request,
            HttpServletRequest httpRequest) {
        
        try {
            // 从请求中获取当前登录医生ID
            Integer doctorId = getCurrentDoctorId(httpRequest);
            if (doctorId == null) {
                return ResponseEntity.badRequest().body(
                    ApiResponse.error("无法获取当前登录医生ID")
                );
            }
            
            // 参数校验
            if (request.getPatientId() == null) {
                return ResponseEntity.badRequest().body(
                    ApiResponse.error("患者ID不能为空")
                );
            }
            
            if (request.getTables() == null || request.getTables().isEmpty()) {
                return ResponseEntity.badRequest().body(
                    ApiResponse.error("要恢复的表列表不能为空")
                );
            }
            
            // 验证请求
            Map<String, Object> result = dataRestoreService.validateRestoreRequest(
                request.getPatientId(), 
                doctorId, 
                request.getTables()
            );
            
            if ((boolean) result.get("valid")) {
                return ResponseEntity.ok(ApiResponse.success(result));
            } else {
                return ResponseEntity.badRequest().body(
                    ApiResponse.error((String) result.get("message"), result)
                );
            }
        } catch (Exception e) {
            logger.error("验证恢复请求时发生错误", e);
            return ResponseEntity.badRequest().body(
                ApiResponse.error("验证恢复请求时发生错误: " + e.getMessage())
            );
        }
    }
    
    /**
     * 从请求中提取医生ID
     */
    private Integer getCurrentDoctorId(HttpServletRequest request) {
        try {
            // 尝试从JWT令牌中提取
            String authHeader = request.getHeader("Authorization");
            if (authHeader != null && authHeader.startsWith("Bearer ")) {
                String token = authHeader.substring(7);
                if (token != null) {
                    return jwtUtil.getUserIdFromToken(token);
                }
            }
            
            // 尝试从 SecurityContext 中提取
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            if (authentication != null && authentication.getPrincipal() != null) {
                // 具体获取方式依赖于你的安全配置
                // 例如，如果Principal是User对象:
                // return ((User) authentication.getPrincipal()).getId();
            }
            
            // 如果都无法获取，可以尝试从请求参数中获取（不推荐）
            String doctorIdParam = request.getParameter("doctorId");
            if (doctorIdParam != null && !doctorIdParam.isEmpty()) {
                return Integer.parseInt(doctorIdParam);
            }
        } catch (Exception e) {
            logger.error("获取当前医生ID时出错", e);
        }
        
        return null;
    }
} 